package cn.yuanqiao.cqbc.dataManage.service.impl;

import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.cqbc.dataManage.domain.Cqdatransdoc;
import cn.yuanqiao.cqbc.dataManage.domain.YqdatransdocLog;
import cn.yuanqiao.cqbc.dataManage.mapper.DocToOfdMapper;
import cn.yuanqiao.cqbc.dataManage.service.DocToOfdService;
import cn.yuanqiao.cqbc.util.OfdAgentCqbc;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 格式转换功能
 *
 * @ProjectName: cn.yuanqiao.cqbc.dataManage.service.impl
 * @ClassName: DocToOfdServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/6/19 09:59
 * @Version: 1.0
 **/
@Service
public class DocToOfdServiceImpl implements DocToOfdService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    DocToOfdMapper docToOfdMapper;
    @Autowired
    private OfdAgentCqbc ofdAgent;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;
    @Value("${YQ.OFD.VERSION}")
    private String transType;

    @Override
    public void docToOfd(JSONObject jsonObject) throws Exception {
        String categoryId = jsonObject.getString("categoryId");
        String daIds = jsonObject.getString("daIds");
        String tenantcode = SecurityUtils.getTenantCode().toUpperCase();
        Map<String, Object> category = docToOfdMapper.queryOne(" ID,NAME, TYPE, EFILE_TABLE_NAME ",
                tenantcode + Constants.BIG_TABLE_NAME, " id ='" + categoryId + "' ");
        String ids = "";
        if (StringUtils.isNotBlank(daIds)) {
            ids = " and CON_TABLE_ID in (" + daIds + ") ";
        }
        List<Map<String, Object>> docDataList = docToOfdMapper.queryList("DOC_ID,PATH,DOC_FILE_TYPE,REAL_DOC_NAME,DOC_MNT,CON_TABLE_ID",
                tenantcode + "_CQBC_HDDADOCUMENT", "CON_TABLE_NAME='" + category.get("EFILE_TABLE_NAME") + "' " + ids);

        Long logId = SnowflakeIdGenerator.generateId();
        YqdatransdocLog logParam = new YqdatransdocLog();
        logParam.setBriefInfo("");
        logParam.setConvertTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        logParam.setConvertNum(String.valueOf(docDataList.size()));
        docToOfdMapper.insertYqdatransdocLog(logParam);
        int num = 0;
        int success = 0;
        for (Map<String, Object> docData : docDataList) {
            File file = new File(docData.get("DOC_MNT").toString() + docData.get("PATH").toString());
            if (file.exists()) {
                //添加转换记录
                Cqdatransdoc cqdatransdoc = new Cqdatransdoc();
                cqdatransdoc.setTransId(SnowflakeIdGenerator.generateId());
                cqdatransdoc.setLogId(logId);
                cqdatransdoc.setDocId((Long) docData.get("DOC_ID"));
                cqdatransdoc.setOriginalUrl(file.getParent());
                cqdatransdoc.setDocName(file.getName());
                cqdatransdoc.setTransType(transType);
                cqdatransdoc.setState(0); //默认失败
                docToOfdMapper.insertYqdatransdoc(cqdatransdoc);
                List<File> docFile = new ArrayList<>();
                docFile.add(file);
                String hz = docData.get("DOC_FILE_TYPE").toString();
                String ofdPath = "";
                if("OCR".equalsIgnoreCase(transType)){
                    ofdPath = file.getParent() + File.separator + "pdf" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".PDF";
                }else{
                    ofdPath = file.getParent() + File.separator + "ofd" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".OFD";
                }
                System.out.println("ofdPath=" + ofdPath);
                if (!new File(ofdPath).getParentFile().exists()) {
                    new File(ofdPath).getParentFile().mkdirs();
                }
                boolean flag = true;
                try {
                    if ("tif".equals(hz.toLowerCase())
                            || "tiff".equals(hz.toLowerCase())
                            || "png".equals(hz.toLowerCase())
                            || "jpg".equals(hz.toLowerCase())) {
                        ofdAgent.imageToOFD(docFile, ofdPath);
                    } else {
                        ofdAgent.officesToOfd(docFile, ofdPath);
                    }
                } catch (Exception e) {
                    flag = false;
                    num++;
                }
                if (flag) {
                    success++;
                }
                save(cqdatransdoc.getTransId(), file.getName(), docData, SecurityUtils.getTenantCode());
            }
        }
        logParam.setSuccessNum("" + success);
        logParam.setBriefInfo(docDataList.size() == success ? "全部转换成功，共" + success + "个文件" : success == 0 ? "全部转换失败，共" + num + "个文件" : "部分文件转换成功，成功" + success + "个文件，失败" + (num) + "个文件");

    }

    private void save(Long transId, String fileName, Map<String, Object> docData, String tenantCode) {
        TransactionStatus transactionStatus = null;
        try {
            //手动开启事务
            transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
            //修改电子文件表
            if(!"OCR".equalsIgnoreCase(transType)){
                Map<String, String> updateDaoc = new HashMap<>();
                updateDaoc.put("TO_OFD", "1");
                docToOfdMapper.updateDocument(updateDaoc, tenantCode + "_CQBC_HDDADOCUMENT", String.valueOf(docData.get("DOC_ID")));
            }
            //添加转换记录
            Cqdatransdoc cqdatransdoc = new Cqdatransdoc();
            cqdatransdoc.setTransId(transId);
            String transUrl = "";
            if("OCR".equalsIgnoreCase(transType)){
                transUrl = docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "pdf" + File.separator
                        + fileName.substring(0, fileName.lastIndexOf(".")) + ".PDF";
            }else{
                transUrl = docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ofd" + File.separator
                        + fileName.substring(0, fileName.lastIndexOf(".")) + ".OFD";
            }
            cqdatransdoc.setTransUrl(transUrl);
            cqdatransdoc.setState(1);
            cqdatransdoc.setTableName(tenantCode + Cqdatransdoc.BIGTABLENAME);
            docToOfdMapper.updateYqdatransdoc(cqdatransdoc);
            dataSourceTransactionManager.commit(transactionStatus);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (transactionStatus != null) {
                dataSourceTransactionManager.rollback(transactionStatus);
            }
        }
    }

    /**
     * 查询转换记录列表
     *
     * @return
     */
    @Override
    public List<YqdatransdocLog> selectYqdatransdocLogList(YqdatransdocLog yqdatransdocLog) {
        return docToOfdMapper.selectYqdatransdocLogList(yqdatransdocLog);
    }

    /**
     * 查询转换记录详情列表
     *
     * @return
     */
    @Override
    public List<Cqdatransdoc> selectYqdatransdocList(Cqdatransdoc cqdatransdoc) {
        return docToOfdMapper.selectYqdatransdocList(cqdatransdoc);
    }

    /**
     * 删除查询转换记录详情
     *
     * @param id
     * @return
     */
    @Override
    public int delYqdatransdoc(String id) {
        return docToOfdMapper.delYqdatransdoc(id,new Cqdatransdoc().getTableName());
    }

    /**
     * 删除转换记录
     *
     * @param id
     * @return
     */
    @Override
    public int delYqdatransdocLog(String id) {
        return docToOfdMapper.delYqdatransdocLog(id,new YqdatransdocLog().getTableName());
    }

}
